<?php
/**
 * [JishiGou] (C)2005 - 2099 Cenwor Inc.
 *
 * This is NOT a freeware, use is subject to license terms
 *
 * @Filename journals.mod.php $
 *
 * @Author http://www.jishigou.net $
 *
 * @Date 2013-05-21 17:04:54 528290859 1992004636 21260 $
 */
if (! defined ( 'IN_JISHIGOU' )) {
	exit ( 'invalid request' );
}
class ModuleObject extends MasterObject {
	var $Member;
	function ModuleObject($config) {
		$this->MasterObject ( $config );
		
		$this->TopicLogic = jlogic ( 'topic' );
		
		if (MEMBER_ROLE_TYPE != 'admin') {
			if (! $this->Config ['journals_open']) {
				exit ( "管理员已关闭游记功能" );
			}
		}
		
		if (MEMBER_ID < 1) {
			exit ( "你需要先登录才能继续本操作" );
		}
		
		$this->Member = $this->_member ();
		
		$this->Execute ();
	}
	function Execute() {
		ob_start ();
		switch ($this->Code) {
			case 'onloadPic' :
				$this->onloadPic ();
				break;
			case 'create' :
				$this->create ();
				break;
			case 'publish_share' :
				$this->publishShare ();
				break;
			case 'simple_talk' :
				$this->simpleTalk ();
				break;
			case 'store' :
				$this->store ();
				break;
			case 'app' :
				$this->app ();
				break;
			case 'need_info' :
				$this->need_info ();
				break;
			case 'manage' :
				$this->manage ();
				break;
			case 'choose' :
				$this->choose ();
				break;
			case 'journalspost' :
				$this->journalsPost ();
				break;
			case 'journalslist' :
				$this->journalsList ();
				break;
			case 'evaluate' :
				$this->evaluate ();
				break;
			default :
				break;
		}
		response_text ( ob_get_clean () );
	}
	function journalsList() {
		$page = empty ( $this->Get ['page'] ) ? 0 : intval ( $this->Get ['page'] );
		$perpage = 8;
		if ($page == 0) {
			$page = 1;
		}
		$start = ($page - 1) * $perpage;
		
		$uid = MEMBER_ID;
		$type = $this->Get ['type'];
		$sys_config = $this->Config;
		if ($type == 'journals') {
			$count = DB::result_first ( "SELECT COUNT(*) FROM " . DB::table ( 'journals' ) . " WHERE postman = '$uid' " );
			if ($count) {
				$list = array ();
				$query = DB::query ( "SELECT id,title
									FROM " . DB::table ( 'journals' ) . "
									WHERE postman = '$uid'
									ORDER BY lasttime DESC
									LIMIT $start,$perpage " );
				while ( $value = DB::fetch ( $query ) ) {
					$value ['journals_url'] = get_full_url ( $sys_config ['site_url'], 'index.php?mod=journals&code=detail&id=' . $value ['id'] );
					$value ['radio_value'] = str_replace ( array (
							'"',
							'\'' 
					), '', $value ['title'] ) . ' - ' . $value ['journals_url'];
					$list [] = $value;
				}
				$multi = ajax_page ( $count, $perpage, $page, 'getMyJournalsList' );
			}
		} else if ($type == 'join') {
			$count = DB::result_first ( "SELECT COUNT(*) FROM " . DB::table ( 'journals_member' ) . " WHERE fid = '$uid' " );
			if ($count) {
				$list = array ();
				$query = DB::query ( "SELECT id,title
									FROM " . DB::table ( 'journals_member' ) . "
									WHERE fid = '$uid'
									ORDER BY play_time DESC
									LIMIT $start,$perpage " );
				while ( $value = DB::fetch ( $query ) ) {
					$value ['journals_url'] = get_full_url ( $sys_config ['site_url'], 'index.php?mod=journals&code=detail&id=' . $value ['id'] );
					$value ['radio_value'] = str_replace ( array (
							'"',
							'\'' 
					), '', $value ['title'] ) . ' - ' . $value ['journals_url'];
					$list [] = $value;
				}
				$multi = ajax_page ( $count, $perpage, $page, 'getJoinJournalsList' );
			}
		}
		
		include (template ( 'journals_list' ));
	}
	function journalsPost() {
		$is_allowed = '';
		if (MEMBER_ID < 1) {
			$is_allowed = "请先登录或者注册一个帐号";
		}
		
		if (MEMBER_ROLE_TYPE != 'admin' && ! $is_allowed) {
			load::logic ( 'journals' );
			$JournalsLogic = new JournalsLogic ();
			$is_allowed = $JournalsLogic->allowedCreate ( MEMBER_ID, $this->Member );
		}
		if ($is_allowed) {
			exit ( $is_allowed );
		}
		
		$item = $this->Get ['item'];
		$item_id = $this->Get ['item_id'];
		$top = 'top';
		$free = 'checked';
		$all = 'checked';
		$info = array ();
		
		$info = ConfigHandler::get ( 'profilejournalsinfo' );
		
		$FormHandler = jlib ( 'form' );
		$query = $this->DatabaseHandler->Query ( "select * from " . TABLE_PREFIX . "journals_sort order by id" );
		while ( $rsdb = $query->GetRow () ) {
			$rs [$rsdb [id]] ['value'] = $rsdb ['id'];
			$rs [$rsdb [id]] ['name'] = $rsdb ['type'];
		}
		$journals_type = $FormHandler->Select ( "type", $rs );
		
		if ($this->Member ['province']) {
			$province_id = DB::result_first ( "select id from " . TABLE_PREFIX . "common_district where name = '" . $this->Member ['province'] . "' and `upid` = '0'" );
		} else {
			$province_id = DB::result_first ( "select id from " . TABLE_PREFIX . "common_district where `upid` = '0' order by list" );
		}
		$query = $this->DatabaseHandler->Query ( "select * from " . TABLE_PREFIX . "common_district where `upid` = '0' order by list" );
		while ( $rsdb = $query->GetRow () ) {
			$province [$rsdb ['id']] ['value'] = $rsdb ['id'];
			$province [$rsdb ['id']] ['name'] = $rsdb ['name'];
		}
		$hid_province = $province_id;
		$province_list = $FormHandler->Select ( "province", $province, $province_id, "onchange=\"changeProvince();\"" );
		
		if ($this->Member ['city']) {
			$city_id = DB::result_first ( "select id from " . TABLE_PREFIX . "common_district where name = '" . $this->Member ['city'] . "' and upid = '$province_id'" );
			$where_city = " and upid = '$city_id' ";
		}
		$hid_city = $city_id;
		
		if ($this->Member ['area']) {
			$area_id = DB::result_first ( "select id from " . TABLE_PREFIX . "common_district where name = '" . $this->Member ['area'] . "' $where_city" );
		}
		$hid_area = $area_id;
		
		$fromt = my_date_format ( TIMESTAMP, 'Y-m-d' );
		$hour_select_from = mk_time_select ( 'hour', false, 'hour_select_from' );
		$min_select_from = mk_time_select ( 'min', false, 'min_select_from' );
		
		$tot = my_date_format ( TIMESTAMP + 7 * 24 * 3600, 'Y-m-d' );
		$hour_select_to = mk_time_select ( 'hour', false, 'hour_select_to' );
		$min_select_to = mk_time_select ( 'min', false, 'min_select_to' );
		
		include (template ( 'journals_publish' ));
	}
	function create() {
		if (! ($this->MemberHandler->HasPermission ( $this->Module, $this->Code ))) {
			json_error ( $this->MemberHandler->GetError () );
		}
		$post = $this->Post;
		if (! $post ['name']) {
			json_error ( "请输入游记标题" );
		}
		$f_rets = filter ( $post ['name'] );
		if ($f_rets && $f_rets ['error']) {
			json_error ( "游记标题" . $f_rets ['msg'] );
		}
		if (! $post ['content1']) {
			json_error ( "请输入游记内容" );
		}
		$f_rets = filter ( $post ['content1'] );
		if ($f_rets && $f_rets ['error']) {
			json_error ( "内容描述" . $f_rets ['msg'] );
		}
		if (! $post ['address']) {
			json_error ( "请输入游记地址" );
		}
		$f_rets = filter ( $post ['address'] );
		if ($f_rets && $f_rets ['error']) {
			json_error ( "游记地址" . $f_rets ['msg'] );
		}
		if (! $post ['hid_pic']) {
			json_error ( "请上传游记封面" );
		}
		$verify = $this->Config ['journals_verify'] ? 0 : 1;
		
		load::logic ( 'journals' );
		$journalsLogic = new JournalsLogic ();
		
		if (MEMBER_ROLE_TYPE != 'admin') {
			$is_allowed = $journalsLogic->allowedCreate ( MEMBER_ID, $this->Member );
		}
		if ($is_allowed) {
			json_error ( $is_allowed );
		}
		
		$item = get_param ( 'item' );
		$item_id = ( int ) get_param ( 'item_id' );
		$return = $journalsLogic->createJournals ( $post, $item, $item_id, $verify );
		
		if (is_array ( $return )) {
			if ($post ['is_draft'] == '1') {
				json_result ( '保存草稿箱成功', array (
				'id' => $post[id]
				) );
			}else{
				json_result ( "修改成功", $return );
			}
		} else {
			$id = $return;
			if ($post ['is_draft'] == '1') {
				json_result ( '保存草稿箱成功', array (
				'id' =>$id
				) );
			}
		}
		
		if (0 == $verify) {
			json_error ( '发布成功，等待管理员审核' );
		}
		
		$value = '我发布了一个游记【' . $post [name] . '】，地址：' . get_full_url ( $this->Config ['site_url'], "index.php?mod=journals&code=detail&id=$id" );
		if ($post ['top'] == 'top') {
			$values = array (
					'id' => $id,
					'content' => $value,
					'from' => '' 
			);
			json_result ( '发布成功', $values );
		}
		$item_id = $id;
		$msg = '发布成功';
		include (template ( 'vote_toweibo' ));
		exit ();
	}
	function publishShare() {
		$id = ( int ) $this->Get ['id'];
		$name = DB::result_first ( "select title from " . TABLE_PREFIX . "journals where id = '$id'" );
		$value = '我觉得游记【' . $name . '】不错，推荐给大家，地址：' . get_full_url ( $this->Config ['site_url'], "index.php?mod=journals&code=detail&id=$id" );
		$item_id = $id;
		include (template ( 'vote_toweibo' ));
		exit ();
	}
	function simpleTalk() {
		$id = ( int ) $this->Get ['id'];
		$item_id = $id;
		$msg = '报名成功';
		$chk_topic_type = 'talk';
		include (template ( 'vote_toweibo' ));
		exit ();
	}
	function store() {
		$id = ( int ) $this->Get ['id'];
		$type = $this->Get ['type'];
		load::logic ( 'journals' );
		$journalsLogic = new JournalsLogic ();
		$journalsLogic->doStroe ( $id, $type );
	}
	function app() {
		load::logic ( 'journals' );
		$JournalsLogic = new JournalsLogic ();
		
		$id = ( int ) $this->Get ['id'];
		$type = $this->Get ['type'];
		$time = TIMESTAMP;
		$rs = $JournalsLogic->get_journals_info ( $id );
		
		if ($rs ['tot'] < TIMESTAMP) {
			json_error ( "游记已截止" );
		} else {
			$user_info = $JournalsLogic->getMemberInfo ( $id );
			if ($type == 'cancle') {
				if ($user_info ['play']) {
					json_error ( "你已参加该游记，请先联系游记发起者取消你的参加资格" );
				} elseif ($user_info ['app'] == 0) {
					json_error ( "你未报名该游记" );
				} else {
					$JournalsLogic->doCancle ( $id );
					json_result ( "取消报名成功" );
				}
			} else {
				if ($user_info ['app'] == 1) {
					json_error ( "你已报名该游记" );
				}
				$qua = unserialize ( $rs ['qualification'] );
				if ($rs ['postman'] != MEMBER_ID) {
					if ($qua ['fans_num']) {
						$fans_num = $this->Member ['fans_count'];
						if ($fans_num < $qua ['fans_num']) {
							json_error ( "报名游记者的粉丝数不能少于" . $qua ['fans_num'] . "人" );
						}
					}
					if ($qua ['same_city']) {
						$city_name = DB::result_first ( "select name from " . TABLE_PREFIX . "common_district where id = '" . ( int ) trim ( $rs ['city_id'] ) . "'" );
						if ($city_name != $this->Member [city]) {
							json_error ( "该游记仅限" . $city_name . "的朋友参与，您当前不符合要求" );
						}
					}
					if ($qua ['inqun']) {
						$inqun = DB::result_first ( "select count(*) from " . TABLE_PREFIX . "qun_user where qid = '{$qua[inqun]}' and uid = '" . MEMBER_ID . "'" );
						if (! $inqun) {
							$qun_name = DB::result_first ( "select name from " . TABLE_PREFIX . "qun where qid = '$qua[inqun]'" );
							json_error ( "该游记仅限<a href='index.php?mod=qun&qid=$qua[inqun]' target='_blank'>" . $qun_name . "</a>的朋友参与，您当前不符合要求" );
						}
					}
				}
				
				$need_info = unserialize ( $rs ['need_app_info'] );
				if (count ( $need_info )) {
					$html = $this->_makeSimpleHtml ( $need_info );
					include (template ( 'need_info' ));
					exit ();
				} else {
					$JournalsLogic->doApp ( $id );
					json_result ( "1" );
				}
			}
		}
	}
	function need_info() {
		load::logic ( 'journals' );
		$JournalsLogic = new JournalsLogic ();
		$id = ( int ) $this->Get ['id'];
		$post = $this->Post;
		$profile = jlogic ( 'member' )->getProfile ();
		$journals_info = $JournalsLogic->get_journals_info ( $id );
		$qua = $journals_info ['need_app_info'];
		
		$qua_info = unserialize ( $qua );
		$qua_arr = array ();
		$time = TIMESTAMP;
		if ($qua_info) {
			foreach ( $qua_info as $key => $val ) {
				if (! $post [$val]) {
					json_error ( "请输入" . $profile [$val] ['title'] );
				}
				if ($profile [$val] ['formtype'] == 'select' && $profile [$val] ['choices']) {
					$choices = explode ( "\r\n", $profile [$val] ['choices'] );
					foreach ( $choices as $v ) {
						list ( $v1, $v2 ) = explode ( "|", $v );
						$v2 || $v2 = $v1;
						$new_choices [$v1] = $v2;
					}
					if ($new_choices [$post [$val]]) {
						$post [$val] = $new_choices [$post [$val]];
					}
					unset ( $new_choices );
				}
				$qua_arr [$profile [$val] ['title']] = $post [$val];
			}
		}
		$qua_arr ['留言'] = $post ['content'];
		
		$qua = serialize ( $qua_arr );
		$JournalsLogic->doApp ( $id, $qua );
		json_result ( "1" );
	}
	function manage() {
		$id = ( int ) $this->Get ['id'];
		
		$page = empty ( $this->Get ['page'] ) ? 0 : intval ( $this->Get ['page'] );
		$perpage = 8;
		if ($page == 0) {
			$page = 1;
		}
		$start = ($page - 1) * $perpage;
		
		$rs = array ();
		$count = DB::result_first ( "select count(*) from " . TABLE_PREFIX . "journals_member where id = '$id' and app = 1" );
		$sql = "select am.fid,m.nickname,am.app_info,am.app_time,am.play from " . TABLE_PREFIX . "journals_member am
				left join " . TABLE_PREFIX . "members m on m.uid = am.fid
				where am.id = '$id'
				and am.app = 1
				order by am.app_time desc
				limit $start,$perpage";
		$multi = ajax_page ( $count, $perpage, $page, 'manage' );
		$query = $this->DatabaseHandler->Query ( $sql );
		while ( $rsdb = $query->GetRow () ) {
			if ($rsdb ['play']) {
				$rsdb ['type'] = "已参加";
				$rsdb ['check'] = 'checked';
			} else {
				$rsdb ['type'] = "尚未审核";
			}
			$rsdb ['app_time'] = date ( "m-d h:i", $rsdb ['app_time'] );
			$app_info = unserialize ( $rsdb ['app_info'] );
			foreach ( $app_info as $key => $value ) {
				$rsdb ['app'] [$key] = $value;
			}
			$rs [$rsdb ['fid']] = $rsdb;
		}
		include (template ( 'journals_manage' ));
		exit ();
	}
	function choose() {
		$post = $this->Post;
		$post ['id'] = ( int ) $post ['id'];
		$type = $this->Get ['type'];
		$time = TIMESTAMP;
		$i = 0;
		if ($type == 'agree') {
			foreach ( $post ['che'] as $key => $val ) {
				$key = ( int ) $key;
				if ($val) {
					$this->DatabaseHandler->Query ( "update " . TABLE_PREFIX . "journals_member set play = 1,play_time = '$time' where id = '{$post[id]}' and fid = '$key'" );
					$i ++;
				}
			}
		} else {
			foreach ( $post ['che'] as $key => $val ) {
				$key = ( int ) $key;
				if ($val) {
					$this->DatabaseHandler->Query ( "update " . TABLE_PREFIX . "journals_member set play = 0,play_time = 0 where id = '{$post[id]}' and fid = '$key'" );
					$i --;
				}
			}
		}
		$play_num = DB::result_first ( "select count(*) from " . TABLE_PREFIX . "journals_member where id = '{$post[id]}' and play = 1 " );
		$this->DatabaseHandler->Query ( "update " . TABLE_PREFIX . "journals set play_num = '$play_num' where id = '{$post[id]}' " );
		json_result ( "成功" );
	}
	function onloadPic() {
		if (! ($this->MemberHandler->HasPermission ( $this->Module, 'create' ))) {
			js_alert_showmsg ( $this->MemberHandler->GetError () );
		}
		if ('admin' != MEMBER_ROLE_TYPE) {
			$is_allowed = jlogic ( 'journals' )->allowedCreate ( MEMBER_ID, $this->Member );
			if ($is_allowed) {
				js_alert_showmsg ( $is_allowed );
			}
		}
		
		Load::lib ( 'image' );
		
		$image = new image ();
		Load::lib ( 'upload' );
		
		if ($_FILES ['pic'] ['name']) {
			$name = time () . MEMBER_ID;
			$image_name = $name . "_b.jpg";
			$image_path = RELATIVE_ROOT_PATH . 'images/journals/';
			$image_file = $image_path . $image_name;
			
			$image_name_show = $name . "_s.jpg";
			$image_file_min = $image_path . $image_name_show;
			
			if (! is_dir ( $image_path )) {
				jlib ( 'io' )->MakeDir ( $image_path );
			}
			
			$UploadHandler = new UploadHandler ( $image_path, 'pic', true );
			$UploadHandler->setMaxSize ( 2048 );
			$UploadHandler->setNewName ( $image_name );
			$result = $UploadHandler->doUpload ();
			
			if ($result) {
				$result = is_image ( $image_file );
			}
			if (! $result) {
				unlink ( $image_file );
				unlink ( $image_file_min );
				echo "<script language='Javascript'>";
				echo "parent.document.getElementById('message').style.display='block';";
				echo "parent.document.getElementById('uploading').style.display='none';";
				if ($this->Post ['top'] == 'top') {
					echo "parent.document.getElementById('back1').style.display='block';";
					echo "parent.document.getElementById('next3').style.display='block';";
				}
				echo "parent.document.getElementById('message').innerHTML='图片上载失败'";
				echo "</script>";
				exit ();
			}
			makethumb ( $image_file, $image_file_min, 60, 60, 0, 0, 0, 0, 0, 0 );
			$image->param ['ignored_animation'] = 0;
			$image->Thumb ( $image_file, $image_file, 150, 150 );
			
			if ($this->Config ['watermark_enable']) {
				jlogic ( 'image' )->watermark ( $image_file );
			}
			
			if ($this->Config ['ftp_on']) {
				$ftp_key = randgetftp ();
				$get_ftps = ConfigHandler::get ( 'ftp' );
				$site_url = $get_ftps [$ftp_key] ['attachurl'];
				$ftp_result = ftpcmd ( 'upload', $image_file, '', $ftp_key );
				if ($ftp_result > 0) {
					ftpcmd ( 'upload', $image_file_min, '', $ftp_key );
					
					jlib ( 'io' )->DeleteFile ( $image_file );
					jlib ( 'io' )->DeleteFile ( $image_file_min );
					
					$image_file = $site_url . '/' . str_replace ( './', '', $image_file );
				}
			}
			
			$hid_pic = $this->Post ['hid_pic'];
			$eid = ( int ) $this->Post ['id'];
			$this->doUnlink ( $hid_pic, $eid );
			
			echo "<script language='Javascript'>";
			echo "parent.document.getElementById('uploading').style.display='none';";
			if ($this->Post ['top'] == 'top') {
				echo "parent.document.getElementById('back1').style.display='block';";
				echo "parent.document.getElementById('next3').style.display='block';";
			}
			echo "parent.document.getElementById('message').style.display='none';";
			echo "parent.document.getElementById('img').style.display='block';";
			echo "parent.document.getElementById('showimg').src='{$image_file}';";
			echo "parent.document.getElementById('hid_pic').value='{$image_file}';";
			echo "</script>";
			exit ();
		}
	}
	function doUnlink($pic) {
		$pic = dir_safe ( $pic );
		if (! $pic)
			return false;
		$pic = str_replace ( array (
				'\\' 
		), array (
				'/' 
		), $pic );
		$pic = str_replace ( array (
				'/' . '/',
				'/./',
				'././' 
		), array (
				'/',
				'/',
				'./' 
		), $pic );
		if (false !== strpos ( $pic, '../' ))
			return false;
		$exp = '~^(\./){0,2}images/journals/\d{10}' . MEMBER_ID . '_b\.(jpg|jpeg|gif|png|bmp)$~';
		if (preg_match ( $exp, $pic )) {
			unlink ( $pic );
			unlink ( strtr ( $pic, '_b.', '_s.' ) );
			return true;
		} else {
			return false;
		}
	}
	function _member() {
		if (MEMBER_ID < 1) {
			$this->Messager ( null, $this->Config ['site_url'] . "/index.php?mod=login" );
		}
		
		$member = jsg_member_info ( MEMBER_ID );
		
		return $member;
	}
	function _makeSimpleHtml($arr) {
		$profile = jlogic ( 'member' )->getProfile ();
		foreach ( $arr as $key => $val ) {
			if (! $profile [$key]) {
				continue;
			}
			$html .= "<tr>";
			if ($profile [$key] ['formtype'] == 'select' && $profile [$key] ['choices']) {
				$detail = explode ( "\r\n", $profile [$key] ['choices'] );
				foreach ( $detail as $val1 ) {
					list ( $v1, $v2 ) = explode ( "|", $val1 );
					$v2 || $v2 = $v1;
					$_html .= "<option value=\"$v1\">$v2</option>";
				}
				$html .= "<td>" . $profile [$key] ['title'] . ":<span style=\"color:red\">*</span></td>
						  <td>
						    <select id=\"" . $profile [$key] ['fieldid'] . "\" name=\"" . $profile [$key] ['fieldid'] . "\">
						     $_html
						    </select>
						  </td>";
				$_html = "";
			} else {
				$html .= "<td>" . $profile [$key] ['title'] . ":<span style=\"color:red\">*</span></td><td><input type=\"text\" id=\"" . $profile [$key] ['fieldid'] . "\" name=\"" . $profile [$key] ['fieldid'] . "\"></td>";
			}
			$html .= "</tr>";
		}
		$html .= "<tr>
				  <td>留言：</td>
				  <td><input type=\"text\" id=\"content\" name=\"content\"></td>
				 </tr>";
		return $html;
	}
	function evaluate() {
		$id = ( int ) $this->Post ['id'];
		if ($id < 1) {
			echo '请选择要评价的游记';
		} else {
			load::logic ( 'journals' );
			$journalsLogic = new JournalsLogic ();
			$return = $journalsLogic->evaluate ( $id, $this->Post ['evaluate'] );
			if ($return === true) {
				// 游记被评价和微博一样+2分
				update_credits_by_action ( 'my_dig', MEMBER_ID );
				echo 'true';
			} else {
				echo $return;
			}
		}
	}
}